
/*
	EVENTS: "update_callback" -> called AFTER an "update" event (tag selected/deselected)

	INTERFACES:
		tagCloud: initialize the object. Required at least once.
		tagCloudAdd: add one (or list) tag
		tagCloudSelect: select one (or list) of tags
		tagCloudDeselect: deselect one (or list) of tags

*/

(function($){

var
	saveTags = function($me){
		var tags = "";
		$me.find(">div:eq(0)>span.tag_selected").each( function(){
				tags += $(this).html() + ",";
			});
		$me.find(">input[type=hidden]").val( tags );
		if ( $me.attr("stop_update") == "dont_stop")
			$me.trigger("cloud_update");
	},

	findTag = function(me, tag){
		var found = false;
		me.find(">div:eq(0)>span.tag").each( function(){
					if ( $(this).html() == tag ){
						found = $(this);
					}
				});
		return found;
	},

	appendTag = function($me, tag){
		if ( !findTag($me,tag) ){
			$me.find(">div:eq(0)").append( $("<span class='tag'>"+tag+"</span>") );
		}
	},

	createNewTag = function(e){
		appendTag(e.data,e.data.find(">div:eq(1)>input[type=text]").val() );
		return false;
	},

	selectTagToggle = function(e){
		$(this).toggleClass("tag_selected");
		saveTags(e.data);
		return false;
	},

	populateTags = function(e,data,error,html){
		var tag;
		for ( tag in data.tags ){
			appendTag( e.data, data.tags[tag] );
		}
		return false;
	};

Core.ObjectTypes["div.tag_cloud"] = function(){
	var $this = $(this);
	$this.attr("stop_update", "dont_stop");

	$this.find(">div:eq(1)>button").bind("click", $this, createNewTag );
	$this.find(">div:eq(0)>span").live("click", $this, selectTagToggle );

	saveTags($this);
	$this.one("cloud_populate", $this, populateTags );
	$this.jsonRequest("MgmBoxes" ,{action:"get_cloud"}, "cloud_populate");
};

$.fn.tagSelect = function( tag ){
	findTag($(this), tag ).addClass("tag_selected");
	saveTags($(this));
};

$.fn.tagUnselect = function( tag ){
	findTag($(this), tag ).removeClass("tag_selected");
	saveTags($(this));
};

$.fn.tagClear = function(){
	$(this).find(">div:eq(0)>span.tag").removeClass("tag_selected");
	saveTags($(this));
};

$.fn.tagCloudGet = function(){
	return $(this).find("input[type=hidden]").val();
};

$.fn.cloudInhibitUpdate = function(){
	$(this).attr("stop_update", "stop");
};

$.fn.cloudAllowUpdate = function(){
	$(this).attr("stop_update", "dont_stop");
};

}(jQuery));
